//
//  QDRecordTableViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/3/1.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit
import HandyJSON

let RecordBackgroundColor = #colorLiteral(red: 0.9803921569, green: 0.9882352941, blue: 0.9803921569, alpha: 1)

/// 记录类型
enum RecordType: String {
    /// 地铁
    case metro = "02"
    /// 公交
    case bus = "04"
}

extension RecordType {
    
    /// 固定行高
    var rowHeight : CGFloat {
        switch self {
        case .metro: return 154
        case .bus: return 78
        }
    }
    
    /// 大标题
    var title: String {
        switch self {
        case .metro: return "地铁乘车记录"
        case .bus: return "公交乘车记录"
        }
    }
    
    /// 按钮的title
    var buttonTitle: String {
        switch self {
        case .metro: return "开发票"
        case .bus: return ""
        }
    }
}

extension RecordType {
    
    /// 没有记录的描述
    var iconTitle: String {
        switch self {
        case .metro: return "暂没有地铁乘车记录"
        case .bus: return "暂没有公交乘车记录"
        }
    }
    
    /// 没有记录的图标
    var iconImage: UIImage? {
        switch self {
        case .metro: return "nothing_record_metro".namedImage
        case .bus: return "nothing_record_bus".namedImage
        }
    }
    
}



///  地铁/公交 乘车记录 
final class QDRecordTableViewController: QDLargeRefreshTitleViewController {

    /// 类型，默认为地铁
    var type = RecordType.metro
    /// 乘车记录数据
    private var listDatas = [QDTrafficModel]()
    
    /// 导航rightItem
    lazy private var rightButtonItem: UIBarButtonItem = {
        
        let button = UIButton()
        button.setTitle("开发票", for: .normal)
        button.adjustsImageWhenHighlighted = false
        button.setTitleColor(/*QDColors.separator*/QDColors.theme, for: .normal)
        button.titleLabel?.font = Font.regular.font(size: 14)
        button.addTarget(self, action: #selector(rightButtonDidTap), for: .touchUpInside)
        
        self.button = button
        return UIBarButtonItem(customView: button)
    }()
    /// 引用rightItem
    private weak var button: UIButton?
    
    
    /// 自己的headerView
    override var largeTableHeaderView: QDLargeTitleTableHeaderView {
        get {
            return largeButtonTableHeaderView
        }set {
            
        }
    }
    
    /// 带按钮的headerView
    let largeButtonTableHeaderView = QDLargeButtonTableHeaderView()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = RecordBackgroundColor
        
        // Do any additional setup after loading the view.
        largeButtonTableHeaderView.backgroundColor = RecordBackgroundColor
        largeButtonTableHeaderView.title = type.title
        largeButtonTableHeaderView.buttonTitle = type.buttonTitle
        largeButtonTableHeaderView.button.setTitleColor(QDColors.theme, for: .normal)
//        largeButtonTableHeaderView.button.isHidden = type == .bus
        largeButtonTableHeaderView.button.isHidden = true
        largeButtonTableHeaderView.isHidden = true
        
        tableView.rowHeight = type.rowHeight
        tableView.showsVerticalScrollIndicator = false
        
        if type == .metro {
            titleForFooterRefreshWithNoMoreData = "只能查询最近一个月内的乘车码乘车记录"
            refreshFooter.setTitle(titleForFooterRefreshWithNoMoreData, for: .noMoreData)
            largeButtonTableHeaderView.button.addTarget(self, action: #selector(rightButtonDidTap), for: .touchUpInside)
        }
        
        requestRecords()
    }
    
    override func registerTableViewCellsAndReusableView() {
        tableView.register(QDRecordBusTableCell.self, forCellReuseIdentifier: RecordType.bus.rawValue)
        tableView.register(QDRecordMetroTableCell.self, forCellReuseIdentifier: RecordType.metro.rawValue)
    }
    
    override func headerRefreshBeginHandler() {
        currentPage = 0
        tableView.mj_footer.resetNoMoreData()
        requestRecords()
    }
    
    override func footerRefreshBeginHandler() {
        requestRecords()
    }
    
    override func tableViewDidScroll(isShow: Bool) {
        
        guard type == .metro else { return }
        
        if !largeButtonTableHeaderView.button.isHidden {//如果存在按钮
            navigationItem.rightBarButtonItem = isShow ? self.rightButtonItem : nil
        }
    }
    
    
    // MARK: Nothing
    override func nothingTitle() -> String? { return type.iconTitle }
    override func nothingImage() -> UIImage? { return type.iconImage }
    
    // MARK: NavigationBar
    override var nav_mutableBarShadowHidden: Bool { return true }
    override var nav_barTintColor: UIColor { return RecordBackgroundColor }
    /// 背景色
    override var tableViewBackgroundColor: UIColor { return RecordBackgroundColor }
    
    /// 请求记录表
    private func requestRecords(){
        
        QDNetworkingManager.requestTrafficRecords(type: type, page: currentPage, complete: { (datas) in
            
            self.endHeaderRefreshing()
            self.endFooterRefreshing()
            
            if self.currentPage == 0 {
                self.listDatas.removeAll()
            }
            
            self.listDatas += datas
            self.tableView.reloadData()
            
            self.currentPage += 1
            if self.listDatas.count < 10 {
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
            }
            
            // 如果数据为0
            if self.listDatas.count == 0 {
                //展示没有乘车记录的数据
                self.showNothingView(true)
                self.largeButtonTableHeaderView.isHidden = true
            }else {
                self.showNothingView(false)
                self.largeButtonTableHeaderView.isHidden = false
            }
        
        }) { (msg, errorType) in
            
            self.endHeaderRefreshing()
            self.endFooterRefreshing()
            self.view.showTextHUD(text: msg)
        }
    }
    
    /// 右侧开发票
    @objc func rightButtonDidTap(){
        print("开发票!")
        router(platform: .bill)
//        ritl_topNavigationPush(QDMetroBillViewController(), animated: true)
    }
}





extension QDRecordTableViewController {

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listDatas.count
    }
    

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: type.rawValue, for: indexPath)
        let traffic = listDatas[indexPath.item]
        
        if let metroCell = cell as? QDRecordMetroTableCell {//表示地铁
            metroCell.updateByMetro(traffic: traffic)
        }
        

        else if let busCell = cell as? QDRecordBusTableCell {//表示公交
            busCell.updateByBus(traffic: traffic)
        }
        
        return cell
    }

    /// 占位headerView
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = RecordBackgroundColor
        return view
    }

    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return section == 0 ? 10 : .leastNormalMagnitude
    }
    
    
    /// 点击时间
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let viewController = QDRecordDetailViewController()
        viewController.type = type
        viewController.traffic = listDatas[indexPath.row]
        navigationController?.pushViewController(viewController, animated: true)
    }
}

extension QDRecordMetroTableCell {
    
    func updateByMetro(traffic: QDTrafficModel){
        
        fillLabel.isHidden = true
        startLabel.text = traffic.entryStationName
        endLabel.text = traffic.exitStationName
        priceLabel.text = "\(NSNumber(value: (Double(traffic.payAmount) ?? 0.0) / 100.0))"
        timeLabel.text = traffic.metroTime
    }

}

extension QDRecordBusTableCell {
    
    func updateByBus(traffic: QDTrafficModel){
        
        titleLabel.text = "公交-\(traffic.uplineid)"
        priceLabel.text = "\(NSNumber(value: (Double(traffic.origAmt) ?? 0.0) / 100.0))元"
        timeLabel.text = traffic.busTime
    }
}



/// 交通
struct QDTrafficModel: HandyJSON {
    
    /// 地铁专用
    
    /// 进站名称
    var entryStationName = ""
    /// 进站时间
    var entryDate = ""
    /// 出站名称
    var exitStationName = ""
    /// 出站时间
    var exitDate = ""
    /// 地铁总价
    var payAmount = ""
    /// 商户订单号
    var tradeOrderNo = ""
    /// 支付方式
    var payChannelCode = ""
    /// 支付时间
    var payOrderNoDate = ""
    
    /// 公交专用

    /// 车辆id
    var uplineid = ""
    /// 车辆编号
    var upTermId = ""
    /// 交易发生日期
    var txnDate = ""
    /// 交易发生时间
    var txnTime = ""
    /// 交易总额
    var txnAmt = ""
    /// 交易编号
    var sysSeq = ""
    /// 公交应收金额
    var origAmt = ""
    /// 支付方式
    var paymentChannel = ""
    /// 支付日期
    var paydate = ""
    /// 支付时间
    var paytime = ""
}

extension QDTrafficModel {
    
    /// 地铁支付方式
    var metroPayType: QDPayType {
        return QDPayType(rawValue: payChannelCode) ?? .unknown
    }
    
    /// 展示的时间
    var metroTime: String { /*20190304127677*/
        get {
            
            let dateFormatter = DateFormatter.cachedDataFormatter(with: "yyyyMMddHHmmss")
            let enterDate = dateFormatter.date(from: entryDate) ?? Date()
            let exitDateString = dateFormatter.date(from: exitDate) ?? Date()
            
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
            let enterString = dateFormatter.string(from: enterDate)
            dateFormatter.dateFormat = "HH:mm"
            let exitString = dateFormatter.string(from: exitDateString)
            
            return "\(enterString)-\(exitString)"
        }
    }
    
    
    /// 地铁支付时间
    var metroPayTime: String {
        get {
            let dateFormatter = DateFormatter.cachedDataFormatter(with: "yyyyMMddHHmmss")
            let date = dateFormatter.date(from: payOrderNoDate) ?? Date()
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
            return dateFormatter.string(from: date)
        }
    }
    
    
    /// 公交的支付方式
    var busPayType: QDPayType {
        return QDPayType(rawValue: paymentChannel) ?? .unknown
    }
    
    /// 展示的时间
    var busTime: String {
        get {
            let dateString = "\(txnDate)\(txnTime)"
            let dateFormatter = DateFormatter.cachedDataFormatter(with: "yyyyMMddHHmmss")
            let date = dateFormatter.date(from: dateString) ?? Date()
            dateFormatter.dateFormat = "MM-dd HH:mm"
            return dateFormatter.string(from: date)
        }
    }
    
    /// 展示的支付时间
    var busPayTime: String {
        get {
            let dateString = "\(paydate)\(paytime)"
            let dateFormatter = DateFormatter.cachedDataFormatter(with: "yyyyMMddHHmmss")
            let date = dateFormatter.date(from: dateString) ?? Date()
            dateFormatter.dateFormat = "MM-dd HH:mm"
            return dateFormatter.string(from: date)
        }
    }
}



extension QDNetworkingManager {
    
    private struct QDTrafficContainer: HandyJSON {
        /// 订单列表
        var orderList = [QDTrafficModel]()
    }
    
    
    /// 请求乘车记录
    static func requestTrafficRecords(type: RecordType = .metro,
                                      page: Int = 0,
                                      complete: @escaping (([QDTrafficModel]) ->()),
                                      fail: QDNetworkingError?){
        
        request(url: QDCustomerHostUrl + "/travel/queryList", paramteres: ["cardType": type.rawValue,"size" : 10, "page": page], success: { (msg, data) in
            
            guard let container = QDTrafficContainer.deserialize(from: data) else {
                fail?("数据解析出错",.unNormal); return
            }
            
            //返回数据
            complete(container.orderList)
            
        }) { (msg, errorType) in
            fail?(msg, errorType)
        }
    }
}

